<template>
  <el-card class="card">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-row :gutter="20">
      <el-col :span="8">
        <el-input
          placeholder="请输入内容"
          v-model="getUsers.query"
          class="input-with-select"
          clearable
          @clear="initGetUsers"
          @keydown.enter.native="initGetUsers"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="initGetUsers"
          ></el-button>
        </el-input>
      </el-col>

      <el-col :span="3">
        <el-button type="success" plain @click="addDialogFormVisible = true"
          >添加用户</el-button
        >
      </el-col>
    </el-row>

    <el-table
      :data="userList"
      style="width: 100%"
      stripe
      border
      v-loading="isLoading"
    >
      <el-table-column type="id" label="序号" prop="id"> </el-table-column>
      <el-table-column prop="create_time" label="日期"> </el-table-column>
      <el-table-column prop="username" label="姓名"> </el-table-column>
      <el-table-column prop="role_name" label="角色"> </el-table-column>

      <el-table-column prop="mobile" label="电话"> </el-table-column>

      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="mg_state" label="用户状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeState(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="caozuo" label="操作" width="340" align="center">
        <template slot-scope="scope">
          <el-tooltip placement="top">
            <div slot="content">编辑按钮</div>
            <el-button
              size="normal"
              @click="handleEdit(scope.$index, scope.row)"
              >Edit</el-button
            >
          </el-tooltip>

          <el-tooltip placement="top">
            <div slot="content">删除按钮</div>
            <el-button
              size="normal"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >Delete</el-button
            >
          </el-tooltip>

          <el-button
            size="normal"
            type="success"
            @click="showGrantDialog(scope.row)"
          >
            角色</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <!-- <span class="demonstration">完整功能</span> -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="getUsers.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="getUsers.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 添加用户dialog -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
      <el-form :model="addForm" :rules="rules" ref="addForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserSubmit('addForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 修改用户dialog -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
      <el-form :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="editForm.username"
            auto-complete="off"
            disabled="disabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserSubmit('editForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="grantDialogFormVisible">
      <el-form :model="grantForm" label-width="120px">
        <el-form-item label="当前的用户：" prop="username">
          <el-tag type="warning">{{grantForm.username}}</el-tag>
        </el-form-item>
        <el-form-item label="请选择角色：">
          <el-select v-model="roleId" placeholder="请选择角色">
            <el-option
              v-for="(role, index) in roleList"
              :key="index"
              :label="role.roleName"
              :value="role.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="grantUserSubmit(roleId)">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  getUsers,
  changeUserState,
  addUsers,
  delUsers,
  getUsersById,
  editUsersById,
  getRoleList,
  changeUserRole
} from "../../api/index";

export default {
  name: "",
  data() {
    return {
      isLoading: false,

      search: "",
      userList: [],
      total: 0,

      getUsers: {
        query: "",
        pagenum: 1,
        pagesize: 10
      },

      // 控制添加用户dialog
      addDialogFormVisible: false,
      // 控制编辑用户dialog
      editDialogFormVisible: false,
      // 控制添加角色dialog
      grantDialogFormVisible: false,

      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      editForm: {
        username: "",
        email: "",
        mobile: ""
      },
      editId: "",

      grantForm: {},
      // 角色列表
      roleList: [],
      // 角色ID
      roleId: "",

      rules: {
        username: [
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur"
          },
          { required: true, message: "请输入名称", trigger: "blur" }
        ],
        password: [
          {
            min: 5,
            max: 11,
            message: "长度在 5 到 11 个字符",
            trigger: "blur"
          },
          { required: true, message: "请输入密码", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱",
            trigger: "blue"
          }
        ],
        mobile: [{ required: true, message: "电话不能为空" }]
      }
    };
  },
  watch: {},
  props: {},
  components: {},
  computed: {},
  mounted() {},
  methods: {
    async initGetUsers() {
      this.isLoading = true;

      let {
        data: { users, total, pagenum }
      } = await getUsers({ params: this.getUsers });
      let res = await getUsers({ params: this.getUsers });
      console.log(res);
      this.userList = users;
      this.total = total;
      this.getUsers.pagenum = pagenum;

      this.isLoading = false;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.getUsers.pagesize = val;
      this.initGetUsers();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.getUsers.pagenum = val;
      this.initGetUsers();
    },

    async handleEdit(index, row) {
      //根据id获取用户信息
      let { data, meta } = await getUsersById(row.id);
      if (meta.status != 200)
        return this.$message.error("获取用户信息失败 请刷新后再试");
      this.editForm.username = data.username;
      this.editForm.email = data.email;
      this.editForm.mobile = data.mobile;
      this.editId = data.id;
      this.editDialogFormVisible = true;
    },

    async handleDelete(index, row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let { data, meta } = await delUsers(row.id);
          console.log(meta);
          if (meta.status != 200) return this.$message.error("删除失败");
          this.$nextTick(() => {
            this.initGetUsers();
          });
        })
        .catch(err => console.log(err));
    },

    handleConfirm(index, row) {
      console.log(index, row);
    },
    async changeState(scope) {
      let { id: uid, mg_state: type } = scope;
      let {
        meta: { status }
      } = await changeUserState({ uid, type });
      console.log(status);
      if (status != 200) this.$message.error("更改状态失败");
      this.initGetUsers();
    },

    addUserSubmit(addform) {
      console.log(addform);
      this.$refs[addform]
        .validate()
        .then(async () => {
          let { data, meta } = await addUsers(this.addForm);
          if (meta.status != 201) return this.$message.error("添加失败");
          this.addForm.username = "";
          this.addForm.password = "";
          this.addForm.email = "";
          this.addForm.mobile = "";
          this.addDialogFormVisible = false;

          this.$nextTick(() => {
            this.initGetUsers();
          });

          console.log(res);
        })
        .catch(err => console.log(err));
    },

    editUserSubmit(editform) {
      console.log(editform);
      this.$refs[editform]
        .validate()
        .then(async () => {
          let { data, meta } = await editUsersById(this.editId, this.editForm);
          console.log(meta);
          console.log(data);
          if (meta.status != 200) return this.$message.error("修改失败");
          this.editForm.username = "";
          this.editForm.email = "";
          this.editForm.mobile = "";
          this.editId = "";
          this.editDialogFormVisible = false;

          this.$nextTick(() => {
            this.initGetUsers();
          });
        })
        .catch(err => console.log(err));
    },

    showGrantDialog(row) {
      this.grantForm = row;
      this.grantDialogFormVisible = true;
      this.roleId = null
      getRoleList().then(res => {
        console.log(res);
        if (res.meta.status === 200) {
          this.roleList = res.data;
        }
      });
    },

   async grantUserSubmit(row) {
      if(!this.roleId) return this.$message.error("角色不能为空")

      let {data,meta} = await changeUserRole({id: this.grantForm.id, rid:this.roleId})
      if(meta.status != 200) return this.$message.error(meta.msg)

       this.grantDialogFormVisible = false;
      if(meta.status == 200) {
        this.initGetUsers()
      return  this.$message.success(meta.msg)
      }
      // console.log(res);
    }
  },
  filters: {},
  created() {
    this.initGetUsers();
  }
};
</script>

<style scoped lang="css">
.el-pagination {
  background: white;
  padding: 20px 0;
  height: 20px;
  line-height: 20px;
}
</style>
